import {Maybe, snCreateUIDom} from 'src/hrpub/common/utils/utils'
import CommonAction from './common';
import {pageTo} from 'nc-lightapp-front';
import {addTempleteQueCon, COMMON, getBillid, getUrlParam, updateButtonStatus} from "../main/util";
import tableRowAddLink from "../../../public/tableRowAddLink";
import {getLangCode} from "../../../public/functions/unit";
import {addPkorgRefer} from "../../../public/functions/addCondition";

// 解决审批中心  以及复制节点的问题
let code = COMMON.appConfig.appcode
if (code.length > 8) {
    code = code.slice(0,8)
}
const reqData = [{
    rqUrl: '/platform/templet/querypage.do',
    rqJson: `{\n  \"pagecode\": \"${COMMON.appConfig.pagecode}\",\n  \"appcode\": \"${COMMON.appConfig.appcode}\"\n}`,
    rqCode: 'template'
}, {
    rqUrl: '/platform/templet/querypage.do',
    rqJson: `{\n  \"pagecode\": \"${code}batch\",\n  \"appcode\": \"${COMMON.appConfig.appcode}\"\n}`,
    rqCode: 'batch_add'
}, {
    rqUrl: '/platform/templet/querypage.do',
    rqJson: `{\n  \"pagecode\": \"60092010cb\",\n  \"appcode\": \"60092010\"\n}`,
    rqCode: 'template_cb'
}, {
    rqUrl: '/platform/appregister/queryallbtns.do',
    rqJson: `{\n  \"pagecode\": \"${COMMON.appConfig.pagecode}\",\n  \"appcode\": \"${COMMON.appConfig.appcode}\"\n}`,
    rqCode: 'button'
}, {
    rqUrl: '/platform/appregister/queryappcontext.do',
    rqJson: `{\n  \"appcode\": \"${COMMON.appConfig.appcode}\"}`,
    rqCode: 'context'
}];

export default class MainAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        if(comp.props.use){
            comp.props.use.form('card','card_batch',"psninfo_batch","newinfo_batch","newinfo_org_batch","contract_mng_org_batch","exeinfo_batch","endinfo_batch");
            comp.props.use.editTable('list','list_batch');
            comp.props.use.search('query','multiadd');
        }
    }

    // 获取多语
    getLanguage = () => {
        const {props} = this.comp;
        const {
            dispatch,
            MultiInit
        } = props;

        MultiInit.getMultiLang({
            moduleId: 'gx6008',
            domainName: 'hrtrn',
            callback: (json, status, init) => {
                dispatch({
                    type: 'transfer/update',
                    payload: {
                        language: json
                    }
                });
            }
        });
    };

    // 获取模版信息
    getTemplate = () => {
        const {props} = this.comp;
        const {
            meta,
            button,
            dispatch
        } = props;

        snCreateUIDom(COMMON.appConfig, reqData, async (res) => {
            await dispatch({
                type: 'transfer/update',
                payload: {
                    context: res.context,
                    templateIdObj: {
                        template: res.template.pageid,
                        batch_add: res.batch_add.pageid,
                    },
                    oid: res.template[COMMON.searchId].oid,
                    oid2: res.batch_add[COMMON.searchId2].oid,
                    formRelation2: res.batch_add.formrelation[COMMON.formId2]
                }
            });
            Object.assign(res.template, {
                [COMMON.addBranch]: res.batch_add[COMMON.addBranch],
                [COMMON.formId2]: res.batch_add[COMMON.formId2],
                [COMMON.searchId2]: res.batch_add[COMMON.searchId2],
                org: res.template_cb['org'],
                dept: res.template_cb['dept'],
            });
            res.batch_add.formrelation[COMMON.formId2].map(key => {
                Object.assign(res.template, {[key]: res.batch_add[key]})
            });
            // 批增查询添加条件
            let search2Tem = res.batch_add[COMMON.searchId2];
            search2Tem.items.map(item => {
                if (item.attrcode === 'hi_psnjob.pk_org' || item.attrcode === 'hi_psnjob.pk_org.code') {
                    if (!item.hasOwnProperty('queryCondition')) {
                        item.queryCondition = {
                            TreeRefActionExt: "nccloud.web.hrhi.pub.sqlbuilder.OrgRefSqlBuilder"
                        };
                    }
                }
            });
            Object.assign(res.template.formrelation, res.batch_add.formrelation);
            this.tableAddOpr(res.template[COMMON.tableId]);
            addTempleteQueCon(res.template);
            this.addSearchInitData(res.template[COMMON.searchId]);
            meta.setMeta(res.template || {}, this.routePage);
            button.setButtons(res.button || []);
        });
    };
    addSearchInitData = (template) => {
        let firstvalue, secondvalue;
        let currDate = new Date();
        let month = currDate.getMonth() + 1;
        let year = currDate.getFullYear();
        let date = currDate.getDate();
        if (month < 10) {
            month = '0' + month;
        }
        if (Number(month) === 1 && date === 1) {
            firstvalue = year - 1 + '-12-31 00:00:00';
        } else {
            firstvalue = year + '-' + month + '-' + '01';
        }
        secondvalue = year + '-' + month + '-' + date;
        let searchDefault = {
            "display": `${firstvalue},${secondvalue}`,
            "value": [firstvalue + ' 00:00:00', secondvalue + ' 23:59:59'],
        };
        template.items.map(item => {
            if (item.attrcode === 'apply_date') {
                item.initialvalue = searchDefault;
            }
        })
    };
    /**
     * 表格添加操作列
     */
    tableAddOpr = (tabledata) => {
        let _this = this;
        let props = this.comp.props;
        let {transfer} = props;
        // 列表页 的组织名称 添加超链接
        tableRowAddLink(tabledata, 'bill_code', this.showDetail, 'value');
        //添加表格操作列
        let event = {
            label: transfer.language["gx6008-000046"],// 操作
            attrcode: 'opr',
            itemtype: 'customer',
            //className: "table-opr",
            fixed: 'right',
            width: '200px',
            visible: true,
            render(text, record, index) {
                let recordVal = record.values;
                return (
                    <div className="currency-opr-col">
                        {props.button.createOprationButton(
                            ['edit', 'copy', 'checkApprOpini'],
                            {
                                area: 'body',
                                onButtonClick: (props, id, e) => {
                                    _this.comp.action.btnAct.headerClick(props, id, 'body', record)
                                },
                                popContainer: document.querySelector('.header2')
                            }
                        )}
                    </div>
                );
            }
        };
        let language = getLangCode();
        let fileWidth = language === 'english' ? "100px" : "80px";
        // 附件
        let fileCol = {
            label: transfer.language["gx6008-000274"], /* 国际化处理： 附件*/
            attrcode: 'file',
            itemtype: 'customer',
            fixed: 'right',
            width: fileWidth,
            visible: true,
            render(text, record, index) {
                const billid = record.values.pk_hi_stapply.value;
                return (
                    <a style={{cursor: 'pointer'}}>
                        <i className="icon iconfont icon-fujianshenpi" onClick={(eve) => {
                            _this.fileManager(billid)
                        }}/>
                    </a>
                )
            }
        };
        tabledata.items.push(fileCol);
        tabledata.items.push(event);
    };

    /**
     * 显示详情页
     * @param record
     * @param index
     */
    showDetail = (record, index) => {
        const billid = getBillid(record);
        this.showDetailPage(billid);
    };

    showDetailPage = async (billid, isEdit = false) => {

        const {props, action} = this.comp;
        const {dispatch} = props;
        await dispatch({
            type: 'transfer/update',
            payload: {
                isEditDetail: isEdit
            }
        });
        action.detailAct.queryDetailData({billid});
    };
    //当是小部件跳转来的话执行的逻辑
    widget = () => {
        const {props, action} = this.comp;
        action.headAct.hrorgChange({refpk: 'widget'})
    }
    // 初始化
    didMount = () => {
        if (window.location.href.match(/(localhost|127\.0\.0\.1):3006/)) window.location.hash = `#ifr?page=2019`;
        // if (window.location.href.match(/(localhost|127\.0\.0\.1):3006/)) window.location.hash = `?c=${COMMON.appConfig.appcode}&scene=approvesce&status=browse&id=1001AB1000000000893H&appcode=60092050&pagecode=60092050nccloud`;
        const {props} = this.comp;
        const {dispatch} = props;
        let {fromScene, status} = getUrlParam(props);
        if (!fromScene && status) {
            fromScene = 'approvesce'
        }
        if (fromScene) {
            dispatch({
                type: 'transfer/update',
                payload: {
                    page: ''
                }
            });
        }
        this.comp.setState({
            tableHeight: window.innerHeight - 145 + 'px'
        });
        this.getTemplate();
        this.getLanguage();
        this.comp.action.btnAct.initPageButton();
        // 统一订阅事件
        this.subscribe();
        let type = pageTo.getUrlParam('type')
        console.log(type);
        if (type) {
            setTimeout(() => {
                this.widget();
            }, 200);
        }

    };

    // 卸载
    willUnMount = () => {
        this.pubSub.unSubscribe('getMainTableData');
    };

    // 根据url判断是进入到编辑页面还是进入到主页面表格
    routePage = () => {
        const {props} = this.comp;
        addPkorgRefer(props, {});
        let {fromScene, id, status} = getUrlParam(props);
        if (!fromScene && status) {
            fromScene = 'approvesce'
        }
        if (!fromScene) {
            return;
        }
        // 更新按钮状态
        updateButtonStatus(props, id, fromScene);

        // 展示详情页
        this.showDetailPage(id, status === 'edit');
    };

    // 事件订阅部分
    subscribe = () => {
        const {comp: {action}, pubSub} = this;
        pubSub.subscribe('getMainTableData', (...args) => {
            action.tableAct.getMainTableData(...args);
        });
        pubSub.subscribe('getWidgetTableData', (...args) => {
            action.tableAct.getWidgetTableData(...args)
        })
    };

    // 确认查询
    toSearch = () => {
        let toast = this.toast;
        const {props} = this.comp;
        const {dispatch} = props;
        const {
            transfer
        } = props;
        let conditions = props.search.getQueryInfo(COMMON.searchId, true);
        dispatch({
            type: 'transfer/update',
            payload: {
                conditions, 
                init: true
            }
        });
        this.comp.action.tableAct.getMainTableData({
            conditions,
            callback: (res) => {
                let num = Maybe.of(res).getValue(['data', COMMON.tableId, 'pageInfo', 'total']) || 0;
                toast({
                    color: 'success',
                    content: transfer.language['gx6008-000121'] + num + transfer.language['gx6008-000122'] // 查询成功
                });
            }
        });
    };

    // 通用关闭弹窗
    closeModal = (field) => {
        return () => {
            const {props} = this.comp;
            const {dispatch} = props;

            dispatch({
                type: 'transfer/update',
                payload: {
                    [field]: false
                }
            });
        }
    };

    // 福建管理
    fileManager = (fileManagerBillId) => {
        const {props} = this.comp;
        const {dispatch} = props;

        dispatch({
            type: 'transfer/update',
            payload: {
                fileManagerBillId,
                fileManagerModalVisible: true
            }
        });
    }
}
